﻿using System;
using BitButterCORE.Extension;

namespace BitButterCORE.Object
{
	public abstract class BasePersistentObject<THeader> : BaseObject
		where THeader : BasePersistentHeader
	{
		public BasePersistentObject(string filepath)
			: this(filepath, null)
		{
		}

		public BasePersistentObject(string filepath, byte[] data)
		{
			FilePath = filepath;
			InitializePersistentObject(data);
		}

		public string FilePath { get; }

		public THeader Header => header ?? (header = (THeader)Activator.CreateInstance(typeof(THeader), FilePath));
		public THeader header;

		public uint Length { get; private set; }

		public byte[] Payload { get; private set; }

		public byte[] Data
		{
			get
			{
				if (data == null && Length > 0)
				{
					data = Payload.PrependLength();
				}
				return data;
			}
		}
		byte[] data;

		public virtual void InitializePersistentObject(byte[] data)
		{
			var headerLength = data.GetPayload(out var headerPayload);
			var objectData = data.TruncateToEnd(headerLength);
			_ = objectData.GetPayload(out var objectPayload);
			SetPersistentData(headerPayload, objectPayload);
		}

		public void SetPersistentData(byte[] headerPayload, byte[] objectPayload)
		{
			Header.SetPersistentData(headerPayload);
			Length = (uint?)objectPayload?.Length ?? 0;
			Payload = objectPayload;
			data = null;
		}
	}
}
